import dataUtil from "db://assets/ccc3-framework-core/framework/modules/dataUtil";
import { CommonUI } from "../../../[框架]/通用UI/CommonUI";
import { TaskDefine } from "../Model/TaskDefine";
import TaskVO from "../Model/TaskVO";
import TaskProxy from "./TaskProxy";
import TaskRecord from "./TaskRecord";
import ADController from "./广告/ADController";
import { CategoryDefine, eventDefine } from "db://assets/scripts/CustomDefine";
import { memoryConfig } from "db://assets/ccc3-framework-core/framework/modules/memoryConfig";
import eventUtil from "db://assets/ccc3-framework-core/framework/modules/eventUtil";

export class TaskManager {

    private static hasInited: boolean = false;
    private static usedAdUnits: string[] = [];
    private static availableAdUnits: string[] = [];

    private static resetAdUnits() {
        this.usedAdUnits = [];
        this.availableAdUnits = TaskProxy.inst.taskConfig.reward_adunits.map(item => item.ad_unit);
    }

    private static getRandomAdUnit(): string {
        if (this.availableAdUnits.length === 0) {
            this.resetAdUnits();
        }

        const randomIndex = Math.floor(Math.random() * this.availableAdUnits.length);
        const selectedAdUnit = this.availableAdUnits[randomIndex];

        this.availableAdUnits.splice(randomIndex, 1);
        this.usedAdUnits.push(selectedAdUnit);

        return selectedAdUnit;
    }

    public static init() {
        if (this.hasInited) {
            return;
        }
        this.hasInited = true;
    }

    public static async doTask(taskVO: TaskVO) {
        if (this.caleCDTime(taskVO) > 0) {
            CommonUI.showModal({
                showCancel: false,
                content: TaskProxy.inst.taskConfig.interval_time,
            });
            return;
        }
        let adUnitID = this.getRandomAdUnit();
        //多个广告位的情况才自动销毁 一个广告位不销毁
        let autoDestory = TaskProxy.inst.taskConfig.reward_adunits.length > 1;
        Guyu.Log.info(`开始播放广告:${adUnitID}`);
        let req = await ADController.requestPlayAd({
            adUnitId: adUnitID,
            autoDestory: autoDestory,
        });
        if (req.status == "cancel") {
            return;
        }
        if (Guyu.RuntimeSDK.onH5) {
            //H5 直接完成
            this.onTaskFinish(taskVO);
            return;
        }
        if (req.canGiveReward) {
            ADController.setLastForceClickFailed(false);
            Guyu.Log.warn("可以发放奖励");
            this.onTaskFinish(taskVO);
            return;
        }
        if (req.requiresForcedClick && !req.hasForcedClickCompleted) {
            ADController.setLastForceClickFailed(true);
            //需要强点，但是没有强点
            CommonUI.showModal({
                showCancel: false,
                content: TaskProxy.inst.taskConfig.not_clickad_tips,
            });
            return;
        }
        if (req.desc) {
            Guyu.AdapterManager.showToast(req.desc);
        }

    }

    public static onTaskFinish(taskVO: TaskVO) {
        TaskRecord.recordAdView(taskVO.m_task_id, taskVO.ad_task_count);
        //记录最后一次完成时间 做时间cd冷却限制
        TaskRecord.recordLastFinishTime();
        Guyu.dispatcher.event(TaskDefine.Events.Task_Update);
        this.sendAwards();
    }

    private static sendAwards() {
        // 发放体力奖励
        let video_fatigue_num = memoryConfig.instance.getIntKey("video_fatigue_num", 3);
        let local_fatigue_num = dataUtil.getUnlockNumByDetailId(1, CategoryDefine.FATIGUE);
        let maxNum = 4;
        let addNum = 0;
        if (local_fatigue_num >= 0) {
            if (local_fatigue_num + video_fatigue_num > maxNum) {
                addNum = maxNum - local_fatigue_num;
                if (addNum <= 0) {
                    addNum = 0;
                }
            } else {
                addNum = video_fatigue_num;
            }
            dataUtil.addUnlock(1, CategoryDefine.FATIGUE, addNum, 0);
            eventUtil.dispatchEvent(eventDefine.FATIGUE_NUM_CHANGED, null);
        }
        if (addNum <= 0) {
            Guyu.AdapterManager.adapter.ui.showToast(`任务完成,当前体力已满`);
            return;
        }
        Guyu.AdapterManager.adapter.ui.showToast(`任务完成,发放${addNum}点体力`);
    }

    public static caleCDTime(taskVO: TaskVO): number {
        let lastTime = TaskRecord.getLastFinishTime();
        if (!lastTime) {
            return 0;
        }
        let taskConfig = TaskProxy.inst.taskConfig;
        let time = Guyu.DayLite.create(Number(lastTime)).add(Number(taskConfig.countdown), "second");
        let now = Guyu.DayLite.now();
        if (now.isAfter(time)) {
            return 0;
        }
        return time.diff(Date.now(), "second");
    }

    public static taskInCd(taskVO: TaskVO): boolean {
        return this.caleCDTime(taskVO) > 0;
    }

}